<?php


namespace App\Http\Controllers\Alipay;
use App\Models\ActivityPage;
use App\Models\AppletsIndex;

use App\Models\AppletsIndexGoodsList;
use App\Models\AppletsIndexListCategory;
use App\Models\AppMiniPlate;
use App\Models\AppTypeModel;
use App\Models\MarketingActive;
use App\Models\Order;
use App\Services\AlipayMiniAppService;
use App\Services\AlipayService;
use App\Services\AntchainAtoService;
use App\Services\CommonService;
use App\Services\EsignService;
use App\Services\NotarizeService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class IndexController extends BaseVerifyController
{


    //收藏配置
    public function getCollectionConfig(Request $request)
    {
        $mini_id=$request->get('mini_id');

        $data = MarketingActive::query()
            ->where('status', 0)
            ->where('mini_id', $mini_id)
            ->where('type',2)
            ->orWhere('is_long', 1)
            ->where('begin_time', '<=', date('Y-m-d H:i:s'))
            ->where('end_time', '>=', date('Y-m-d H:i:s'))
            ->select('id', 'title', 'content', 'create_time','color','label')->get();

        if (!$data) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '数据不存在');
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    public function getMarketingActivity(Request $request)
    {
        $input = $request->input();
        if (empty($input['id'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '缺少参数');
        }
        $data = MarketingActive::query()->where('id', $input['id'])
            ->where('begin_time', '<=', date('Y-m-d H:i:s'))
            ->where('end_time', '>=', date('Y-m-d H:i:s'))
            ->select('id', 'title', 'content', 'create_time','color','image','image_a','label')->first();
        if (!$data) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '数据不存在');
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    /**
     * 小程序首页数据
     * @param Request $request
     * @return false|string
     */
    public function index(Request $request){
        $page = $request->input('page',1);
        $pageSize = AppletsIndex::CACHE_LIMIT_NUM;
        $data = '';//Redis::hget(AppletsIndex::REDIS_KEY,$page)
        if($data){
            $list = json_decode($data,true);
        }else{
            $limitData = AppletsIndex::where(['status'=>AppletsIndex::STATUS_YES_SHOW,'is_release'=>AppletsIndex::RELEASE_ONLINE_YES])
                ->orderBy('type','asc')
                ->paginate($pageSize);
            $list = obToArray($limitData);
            if($list){
                Redis::hset(AppletsIndex::REDIS_KEY,$page,json_encode($list));
            }
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$list);
    }

    /**
     * 获取小程序配置
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|string
     */
    public function getMiniPlate(Request $request){
        $mini_id=$request->get('mini_id');
        $group=$request->get('group');
        if(empty($group)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '缺少参数');
        }
        $data=AppMiniPlate::getAlipayMiniPlate($mini_id,$group);



        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
    }
    public function getMiniName(Request $request){
        $mini_id=$request->get('mini_id');
        $app_name=AppTypeModel::query()->where('id',$mini_id)->value('app_name');
        if(!empty($mini_id)&&$mini_id==10009){
            $open=0;
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',compact('app_name','open'));
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$app_name);
        }

    }

    /**
     * 首页推荐分类列表
     * @return false|string
     */
    public function listCategoryList(){
        $category = Redis::get(AppletsIndexListCategory::REDIS_CATEGORY_KEY);
        $category = json_decode($category,true);
        if(empty($category)){
            $category = AppletsIndexListCategory::getList();
            if($category){
                Redis::set(AppletsIndexListCategory::REDIS_CATEGORY_KEY,json_encode($category));
            }
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$category);
    }

    /**
     * 首页推荐分类商品列表
     * @param Request $request
     * @return false|string
     */
    public function indexList(Request $request){
        $cateId = $request->input('cateId','');
        $page = $request->input('page','1');
        $pageSize = $request->input('pageSize',AppletsIndexGoodsList::CACHE_LIMIT_NUM);
        $list = [];
        if(empty($cateId)){
            $category = Redis::get(AppletsIndexListCategory::REDIS_FIRST_CATEGORY_KEY);
            $category = json_decode($category,true);
            if(empty($category)){
                $category = AppletsIndexListCategory::getFirstList();
            }
            if($category){
                $cateId = $category['id'];
            }
        }
        if(!empty($cateId)){
            $list = Redis::hget(AppletsIndexGoodsList::REDIS_LIST_KEY,$cateId.'-'.$page);
            if($list){
                $list = json_decode($list,true);
            }else{
                $list = AppletsIndexGoodsList::getList($cateId,$page,$pageSize);
                if($list){
                    Redis::hset(AppletsIndexGoodsList::REDIS_LIST_KEY,$cateId.'-'.$page,json_encode($list));
                }
            }
        }

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$list);
    }



    //根据id获取活动分类 http://shop.cn/Alipay/Index/getActivityPageById?id=
    public function getActivityPageById(Request $request)
    {
        $input = $request->input();
        if (empty($input['id'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '缺少参数');
        }
        $data = Redis::hget(ActivityPage::ACTIVITY_PAGE_KEY, $input['id']);
        if ($data) {
            $data = json_decode($data, true);
        } else {
            $data = ActivityPage::GetOneActivityPage(array('id' => $input['id'],'status' => ActivityPage::ACTIVITY_PAGE_STATUS_PUBLISHED));
            if (!empty($data)) {
                Redis::hset(ActivityPage::ACTIVITY_PAGE_KEY, $input['id'], json_encode($data));
            }
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    /**
     * 电子合同查询
     * @param Request $request
     * @return false|string
     */
    public function querySignFlow(Request $request){
        $order_id = $request->input('order_id');
        $order = Order::from('sp_order_2 as o')
            ->where('o.id',$order_id)
            ->leftjoin('sp_member_2 as u','o.uid','u.id')
            ->leftjoin('sp_shop_user_2 as su','o.seller_id','su.member_id')
            ->leftjoin('sp_order_goods_2 as og','o.id','og.order_id')
            ->leftjoin('sp_goods_2 as g','og.goods_id','g.id')
            ->select(
                'o.id','o.trade_no','o.begin_time','o.zulinbao_order_id','o.end_time','o.pact_url_3','o.pact_url','o.uid','o.seller_id','o.is_insurance_choose',
                'o.flow_id','o.mobile','o.user_email','o.sign_num','o.address','o.rent_total','o.month_total','o.amount','o.realname','o.rent_total',
                'o.foregift','o.status','o.prov','o.city','o.area','o.sign_status','o.is_rent_choose'
                ,'o.create_time'
                ,'u.ant_user_id','u.mobile as user_mobile','u.id as x_user_id','u.cert_name','u.user_id','u.cert_no','u.esign_user_id'
                ,'u.idcard_front','u.idcard_back','og.id as order_goods_id ','og.pact_type','og.is_buy_out','og.goods_title','og.setmeal_title',
                'og.lease_set','og.setmeal_price','og.setmeal_foregift','o.prepayment_total','o.pact_url',
                'og.goods_id','og.setmeal_id','og.id as order_goods_id','og.spec_id','og.lease_price','og.lease_time','og.website_price','og.start_date'
                ,'su.mechanism','su.faname','su.shopname','su.contact_tel','su.company','su.company_area','su.companyid','su.id as shop_user_id'
                ,'su.ant_user_id as mer_ant_id','o.sign_no','su.esign_seal_id','su.ant_seal_id','o.prepayment_total' ,'g.new_grade')
            ->first();
        $order = $order ? $order->toArray() : [];
        if($order) {
            $res= AntchainAtoService::querySignFlow($order['sign_no']);

            $docList=json_decode($res['docList'],true);
            if($res['resultCode']=='OK'&&$res['status']=='FINISH'&&empty($order['pact_url'])){
                $fileUrl = $docList[0]['downloadUrl'];
                $fileName = $res['flowId'].".pdf";
                $file = file_get_contents($fileUrl);
                $path = dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/storage/tmp/'.$fileName;

                file_put_contents($path,$file);
                $uploud_res = AlipayService::upload($fileName,$path);
                if($uploud_res['status']){
                    if(file_exists($path)){
                        unlink($path);
                    }
                }
                $order_data['sign_no']=$res['signNo'];
                $order_data['pact_url'] = $fileName;
                $order_data['sign_status']  = EsignService::ESIGN_STATUS_FINISH;
                Order::where('id',$order['id'])->update($order_data);

                $order['pact_url'] = $fileName;
//                NotarizeService::uploadOrderInfo($order);
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功');
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, $res['resultMsg']);
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
    }
}
